<!-- 当前模块：登录 -->
<template>
  <div class="page_login">
    <img src="../../../static/images/mine/avatar.png" alt=""/>
    <div class="login_form">
      <van-field v-model="form.username" type="number" label="手机号" placeholder="请输入手机号" @change="val=>handleChange(val, 'username')"></van-field>
      <van-field type="password" v-model="form.password" label="密码" placeholder="请输入密码" @change="val=>handleChange(val, 'password')"></van-field>
    </div>
    <van-button type="info" size="default" block @click="handleLoginFn">立即登录</van-button>
    <div style="margin-bottom: 12px;"></div>
    <van-button block open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">授权登录</van-button>
  </div>
</template>

<script>
import {api} from "../../utils/api"
import { appId } from "../../plugins";
export default {
  data () {
    return {
        form: {
          appId: appId,
          code: "",
          username: "",
          password: ""
        },
        freshKey: ''
    }
  },
  onShow() {
    this.freshKey = new Date().getTime();
  },
  methods: {
    handleChange({mp}, key) {
      let { detail } = mp;
      this.form[key] = detail;
    },
    /**获取手机号权限 */
    async getPhoneNumber({mp}) {
      wx.showLoading({ title: '加载中', mask: true });
      const {encryptedData, iv, code} = mp.detail;
      if(encryptedData && iv) {
        this.getWxCode(async ()=>{
          let data = {
            appId: appId,
            code: this.form.code,
            phoneCode: code,
            userInfo: {}
          }
          const res = await api.loginWx(data);
          this.form.username = "";
          this.form.password = "";
          if(res.result == 0) {
            this.$store.dispatch('setIsLogin', true);
            this.$store.dispatch('setToken', res.token);
            this.$store.dispatch('setUserInfo', res.userInfo);
            this.$store.dispatch('setCommunityId', res.userInfo.communityId);
            wx.navigateBack();
          }else {
            wx.showToast({
              title: "授权失败",
              icon: "none"
            });
          }
          setTimeout(() => { wx.hideLoading(); }, 500);
        })
      } else {
        setTimeout(() => { wx.hideLoading(); }, 500);
      }
    },
    getWxCode(cb) {
      wx.login({
        success: res=>{
          this.form.code = res.code;
          if(cb) {
            cb();
          }
        },
        fail: err => {
          setTimeout(() => {
            wx.hideLoading();
          }, 500);
        }
      })
    },
    /**立即登录按钮事件 */
    async handleLoginFn() {
      if(!this.form['username']) {
        wx.showToast({
          title: "手机号不得为空",
          icon: "none"
        })
        return;
      } else if(!this.form['password']) {
        wx.showToast({
          title: "密码不得为空",
          icon: "none"
        })
        return;
      }
      wx.showLoading({ title: '加载中', mask: true });
      this.getWxCode(async ()=>{
        const res = await api.login(this.form);
        if(res.code == 0) {
          this.$store.dispatch('setIsLogin', true);
          this.$store.dispatch('setToken', res.token);
          this.$store.dispatch('setUserInfo', res.owner);
          this.$store.dispatch('setCommunityId', res.owner.communityId);
          this.form.username = "";
          this.form.password = "";
          wx.navigateBack();
        } else {
          wx.showToast({
            title: res || '请求失败',
            icon: "none"
          })
        }
        setTimeout(() => { wx.hideLoading(); }, 500);
      });
    }
  },
  onShareAppMessage() {
    return {
      title: '智慧养老',
      path: '/pages/auth/main',
      from: "menu" 
    }
  }
}
</script>

<style scoped>
.page_login {
  text-align: center;
  padding: 0 24rpx;
}
.page_login img {
  width: 160rpx;
  height: 160rpx;
  margin: 120rpx 0;
}
.login_form {
  text-align: left;
  margin-bottom: 48rpx;
}
</style>
